const router = require("express").Router();
const mysql = require("../mysql");
const Favorite = require("../mysql/collection/Favorite");
const Product = require("../mysql/collection/Product");
const jwt = require("jsonwebtoken");

/**
 * @api {post} /api/favorite/add 添加收藏
 * @apiName PostFavoriteAdd
 * @apiGroup Favorite
 * @apiHeader {String} token  token
 * @apiParam {String} userid 用户id
 * @apiParam {String} proid 商品id
 * @apiSuccessExample {json} Success-Response:
 *  {
 *    code: '200',
 *    message: '收藏成功'
 *  }
 */
// 添加收藏
router.post("/add", (req, res, next) => {
  let { proid } = req.body;
  let userid = req.decoded.userid; // 从JWT token中获取userid
  
  if (
    proid === "" ||
    proid === undefined
  ) {
    res.send({
      code: "10101",
      message: "请填写完整参数",
    });
    return;
  }

  // 检查商品是否存在
  mysql.find(Product, { proid }, { _id: 0, __v: 0 }).then((productData) => {
    if (productData.length === 0) {
      res.send({
        code: "10102",
        message: "商品不存在",
      });
      return;
    }

    // 检查是否已经收藏
    mysql.find(Favorite, { userid, proid }, { _id: 0, __v: 0 }).then((data) => {
      if (data.length > 0) {
        res.send({
          code: "10103",
          message: "已经收藏过该商品",
        });
      } else {
        // 添加收藏
        const insertData = {
          userid,
          proid,
          createtime: new Date(),
        };
        mysql.insert(Favorite, insertData).then(() => {
          res.send({
            code: "200",
            message: "收藏成功",
          });
        }).catch((err) => {
          res.send({
            code: "10104",
            message: "收藏失败",
          });
        });
      }
    }).catch((err) => {
      res.send({
        code: "10105",
        message: "查询收藏状态失败",
      });
    });
  }).catch((err) => {
    res.send({
      code: "10106",
      message: "查询商品失败",
    });
  });
});

/**
 * @api {post} /api/favorite/remove 取消收藏
 * @apiName PostFavoriteRemove
 * @apiGroup Favorite
 * @apiHeader {String} token  token
 * @apiParam {String} userid 用户id
 * @apiParam {String} proid 商品id
 * @apiSuccessExample {json} Success-Response:
 *  {
 *    code: '200',
 *    message: '取消收藏成功'
 *  }
 */
// 取消收藏
router.post("/remove", (req, res, next) => {
  const { proid } = req.body;
  const userid = req.decoded.userid; // 从JWT token中获取userid
  
  if (
    proid === "" ||
    proid === undefined
  ) {
    res.send({
      code: "10101",
      message: "请填写完整参数",
    });
    return;
  }

  mysql.delete(Favorite, { userid, proid }).then(() => {
    res.send({
      code: "200",
      message: "取消收藏成功",
    });
  }).catch((err) => {
    res.send({
      code: "10107",
      message: "取消收藏失败",
    });
  });
});

/**
 * @api {post} /api/favorite/list 获取收藏列表
 * @apiName PostFavoriteList
 * @apiGroup Favorite
 * @apiHeader {String} token  token
 * @apiParam {String} userid 用户id
 * @apiSuccessExample {json} Success-Response:
 *  {
 *    code: '200',
 *    message: '收藏列表',
 *    data: []
 *  }
 */
// 获取收藏列表
router.post("/list", (req, res, next) => {
  const userid = req.decoded.userid; // 从JWT token中获取userid

  mysql.find(Favorite, { userid }, { _id: 0, __v: 0 }).then((data1) => {
    if (data1.length === 0) {
      res.send({
        code: "200",
        message: "收藏列表为空",
        data: [],
      });
    } else {
      // 获取收藏的商品详情
      const arr = [];
      data1.forEach((item, index) => {
        arr.push(
          mysql.find(Product, { proid: item.proid }, { _id: 0, __v: 0 })
        );
      });

      Promise.all(arr).then((result) => {
        const resultarr = [];
        result.forEach((item, index) => {
          if (item[0]) {
            let obj = {};
            // 从收藏数据库获取
            obj.userid = data1[index].userid;
            obj.proid = data1[index].proid;
            obj.createtime = data1[index].createtime;
            // 从商品数据库获取
            obj.img1 = item[0].img1;
            obj.proname = item[0].proname;
            obj.originprice = item[0].originprice;
            obj.discount = item[0].discount;
            obj.sales = item[0].sales;
            obj.stock = item[0].stock;
            obj.issale = item[0].issale;
            resultarr.push(obj);
          }
        });
        res.send({
          code: "200",
          message: "收藏列表",
          data: resultarr,
        });
      }).catch((err) => {
        res.send({
          code: "10108",
          message: "获取商品详情失败",
        });
      });
    }
  }).catch((err) => {
    res.send({
      code: "10109",
      message: "获取收藏列表失败",
    });
  });
});

module.exports = router;